<template>
  <div style="width: 100vw; height: 100vh; margin: 0 auto; overflow: hidden">
    <svg-prview
      :component_infos="component_infos"
      :svg_data="prview_data"
      :svgCanvas="{ width: tWidth, height: tHeight }"
      :backgroundColor="tBackgroundColor"
    ></svg-prview>
  </div>
</template>

<script setup lang="ts">
import SvgPrview from "../../components/SvgPrview.vue";
import axios from "axios";
import { reactive, ref } from "@vue/reactivity";
import { useRoute } from "vue-router";
import Cookies from "js-cookie";
import { getCurrentInstance, inject } from "vue";
import { ElMessage } from "element-plus";
import { Mqtt } from "../../utils/mqtt";
import { getList, getTopoById } from "@/api/business";
const host = "ws://10.1.10.32:8083/mqtt";
const option = {
  clientId: "smart_client" + Math.random(),
  username: null,
  password: null,
  clean: true, //离线时是否接收 QoS 1 和 2 的消息 false 为接收,true为不接收
  reconnectPeriod: 5000, //重连时间间隔
};

const mqtt = new Mqtt(host);
mqtt.connect(option);
const route = useRoute();
const nodeList: Array<any> = reactive([]); //页面点位数组
const valueList = reactive([]); //接口获取点位数据数组
const tid = route.query[Object.keys(route.query)[0]];
const handelSingleNodeKey = (svg, value) => {
  //处理单点位svg数据逻辑

  let mutlNodeFlag = false; //用来判断是不是多点位
  if (Array.isArray(value)) {
    mutlNodeFlag = true;
  }
  //进制转换特性
  if (svg.active.hasOwnProperty("active_conversion")) {
    let con = svg.active.active_conversion.alarm[0].conversion.val.selectval;
    let index = svg.active.active_conversion.alarm[0].expression.val;
    if (con == 2) {
      //二进制转换
      if (mutlNodeFlag)
        //如果是多点位
        value[index] = value[index].toString(2);
      else {
        value = parseInt(value).toString(2).split("").reverse();
        for (let i = 0; i < 10; i++) {
          //二进制补0
          value.push(0);
        }
      }
    } else if (con == 16) {
      //十六进制转换
      if (mutlNodeFlag)
        //如果是多点位
        value[index] = value[index].toString(16);
      else value = parseInt(value).toString(16).split("").reverse();
    }
  }
  if (svg.type === "TextSvg") {
    //文本直接赋值
    if (svg.active.hasOwnProperty("active_DVtrans")) {
      //判断是否有值转动态属性
      let text = eval(svg.active.active_DVtrans.alarm[0].expression.val);
      svg.extend_attr.text.val = text;
    } else {
      if (mutlNodeFlag) {
        //如果是多点位,默认绑定最后一个
        svg.extend_attr.text.val = value[value.length - 1];
      } else svg.extend_attr.text.val = value;
    }
  }
  //动态属性
  if (
    svg.active.hasOwnProperty("active_color") &&
    svg.active?.active_color?.val?.selectval
  ) {
    svg.active.active_color.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        if (svg.extend_attr.color) svg.extend_attr.color.val = kk.color.val;
        else if (svg.extend_attr.fill) svg.extend_attr.fill.val = kk.color.val;
        else if (svg.extend_attr.fillcolor)
          svg.extend_attr.fillcolor.val = kk.color.val;
      }
    });
  }

  //switch效果状态
  if (svg.active.hasOwnProperty("active_switch")) {
    svg.active.active_switch.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.extend_attr.switch.val.selectval = kk.switch.val.selectval;
      }
    });
  }

  //旋转效果，动画方式
  if (svg.active?.active_rotate?.val?.selectval) {
    svg.active.active_rotate.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.extend_attr.class.val = kk.animation.val.selectval;
      }
    });
  }
  //旋转效果，变换方式translate
  if (svg.active?.active_translate_rotate?.val?.selectval) {
    svg.active.active_translate_rotate.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.angle = kk.angle.val;
      }
    });
  }
  //图片切换
  if (svg.active?.active_changeSrc?.val?.selectval) {
    svg.active.active_changeSrc.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.extend_attr.src.val = kk.src.val;
      }
    });
  }

  //显示、隐藏
  if (svg.active?.active_show?.val?.selectval) {
    svg.active.active_show.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.extend_attr.show.val = kk.show.val.selectval;
      }
    });
  }
  //X位移
  if (svg.active?.active_Xtranslate?.val?.selectval) {
    let xLastPosition = svg.active.active_Xtranslate.lastPosition; //上次的位置
    let xStep = svg.active?.active_Xtranslate?.alarm[0].expression.val; //x轴位移步长
    let val = 0; //实际位移绑点值
    if (mutlNodeFlag) {
      //多点的话需要确定是哪个点
      val = parseFloat(
        eval(svg.active?.active_Xtranslate?.alarm[1].expression.val)
      );
    } else val = parseFloat(value);
    let len = val - parseFloat(xLastPosition);

    svg.svgPositionX += len * parseFloat(xStep);
    svg.active.active_Xtranslate.lastPosition = parseFloat(value);
  }
};
const handelMutlNodeKey = (svg, valList) => {
  handelSingleNodeKey(svg, valList);
};
//页面初始化接口,需要传nodeKey数组
const initData = (nodeList: Array<Object>) => {
  mqtt_info();
};

//图库json数据
const component_infos = ref([]);
//要预览的数据
const prview_data = ref<any>([]);
//当前页面的toptic的数组
const topicList = ref("");
//获取组件列表
axios.get("json/InterfaceReturn.json").then((res) => {
  component_infos.value = res.data;
});
let tWidth = ref(1710);
let tHeight = ref(860);
let tBackgroundColor = ref(null); //画布背景颜色
//传入参数，获取页面数据
if ("" != tid) {
  // const backendUrl = getCurrentInstance()?.appContext.config.globalProperties.$backendUrl
  getTopoById(tid).then((res) => {
    if (res.code == 200 && res.data != "") {
      tWidth.value = (res.data[0] as any).t_width;
      tHeight.value = (res.data[0] as any).t_height;
      var svgdata = (res.data[0] as any).t_jsondata;
      prview_data.value = JSON.parse(svgdata);
      // prview_data.value = res.data;
      topicList.value = (res.data[0] as any).t_topic;
      tBackgroundColor.value = (res.data[0] as any).t_background_color;
      getDefaultConfig();
    } else {
      alert("调用后端失败");
    }
  });
}

//有动态效果的文字SVG
const TextSvgList = ref<any>([]);
//有动态效果的非文字SVG
const allActiveList = ref<any>([]);
//获取本页面默认数据列表
const getDefaultConfig = () => {
  let temp: Array<any> = [...prview_data.value];
  //找到所有的文字
  TextSvgList.value = temp.filter(
    (f) => f.active_type == "text" && f.nodeKey !== ""
  );
  allActiveList.value = temp.filter((f) => f.nodeKey !== "");
  allActiveList.value.forEach((e) => {
    if (e.nodeKey.indexOf(",") === -1) {
      nodeList.push({ id: e.id, type: "single", nodeKey: e.nodeKey, svg: e }); //单个点位直接入数组
    } else {
      if (e.nodeKey.indexOf("|") !== -1) {
        let arrList = [];
        let keyList = [];
        arrList = e.nodeKey.split("|");
        arrList.forEach((e) => {
          if (e.length) keyList.push(e.split(","));
        });
        nodeList.push({
          id: e.id,
          type: "mutlGroup",
          nodeKey: keyList,
          svg: e,
        }); //多组多点位数组
      } else
        nodeList.push({
          id: e.id,
          type: "mutlPoint",
          nodeKey: e.nodeKey.split(","),
          svg: e,
        }); //多点位拆分入node
    }
  });
  initData(nodeList); //页面统一初始化接口
};
const mqtt_info = () => {
  let topic = [];
  topic = topicList.value.split(",");
  mqtt.subscribe(topic, 0); //订阅topic

  topic.forEach((t) => {
    mqtt.message_callback(t, (topic: string, payload: Buffer) => {
      let payloadData = JSON.parse(payload.toString());
      if (Array.isArray(payloadData)) {
        payloadData.forEach((p) => {});
      } else {
        nodeList.forEach((node) => {
          if (node.nodeKey.trim() == payloadData.nodeKey.trim()) {
            handelSingleNodeKey(
              node.svg,
              parseFloat(payloadData.value).toFixed(1)
            );
          }
        });
      }
    });
  });
};
</script>
